package org.cogaen.java2d.xml;

import java.awt.Color;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class ColorParser {

	private static final String COLOR_ELEMENT = "color";
	private static final String RED_ATTRIB = "red";
	private static final String GREEN_ATTRIB = "green";
	private static final String BLUE_ATTRIB = "blue";
	private static final String ALPHA_ATTRIB = "alpha";
	private static final int MAX_VALUE = 255;
	private static final int MIN_VALUE = 0;
	private Color color;

	public static boolean isStart(XMLStreamReader reader) {
		return reader.isStartElement() && COLOR_ELEMENT.equals(reader.getLocalName());
	}
		
	public static ResetableStreamFilter createFilter(String colorName) {
		return new ElementFilter(COLOR_ELEMENT, colorName);
	}
	
	private void reset() {
		this.color = null;
	}
		
	public void parse(XMLStreamReader reader) throws XMLStreamException, ParseException {
		reset();
		
		if (isStart(reader)) {
			int red = parseComponent(reader, RED_ATTRIB);
			int green = parseComponent(reader, GREEN_ATTRIB);
			int blue = parseComponent(reader, BLUE_ATTRIB);
			int alpha = parseComponent(reader, ALPHA_ATTRIB);
			
			if (alpha < MAX_VALUE) {
				this.color = new Color(red, green, blue, alpha);			
			} else {
				this.color = new Color(red, green, blue);			
			}
		} else {
			throw new ParseException("xml element not found");
		}
	}
	
	private int parseComponent(XMLStreamReader reader, String attr) throws ParseException {
		String str = reader.getAttributeValue(null, attr);
		
		if (str == null) {
			return MAX_VALUE;
		}
		
		try {
			int value = Integer.parseInt(str);
			if (value > MAX_VALUE || value < MIN_VALUE) {
				throw new ParseException("invalid value for color component '" + str + "'");				
			}
			return value;
		} catch (NumberFormatException e) {
			throw new ParseException("invalid value for color component '" + str + "'");
		}		
	}

	public Color getColor() {
		return this.color;
	}	
}
